package com.unlcn.ils.wms.backend.service.borrow.impl;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.QiniuUtil;
import com.unlcn.ils.wms.backend.bo.outboundBO.BarCodeBO;
import com.unlcn.ils.wms.backend.enums.*;
import com.unlcn.ils.wms.backend.service.borrow.WmsBorrowCarService;
import com.unlcn.ils.wms.backend.service.inbound.WmsBatchNoService;
import com.unlcn.ils.wms.backend.service.outbound.impl.WmsShipmentPlanServiceImpl;
import com.unlcn.ils.wms.backend.util.ZxingEAN13Handler;
import com.unlcn.ils.wms.base.dto.*;
import com.unlcn.ils.wms.base.mapper.additional.WmsInventoryExtMapper;
import com.unlcn.ils.wms.base.mapper.additional.WmsInventoryLocationExtMapper;
import com.unlcn.ils.wms.base.mapper.additional.wmsOutbound.WmsOutboundTaskExtMapper;
import com.unlcn.ils.wms.base.mapper.additional.wmsOutbound.WmsPreparationPlanExtMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.*;
import com.unlcn.ils.wms.base.mapper.outbound.WmsPreparationPlanMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsBorrowCarDetailMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsBorrowCarMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsInventoryLocationMapper;
import com.unlcn.ils.wms.base.model.outbound.WmsOutboundTask;
import com.unlcn.ils.wms.base.model.outbound.WmsPreparationPlan;
import com.unlcn.ils.wms.base.model.outbound.WmsPreparationVehicleDetail;
import com.unlcn.ils.wms.base.model.stock.*;
import jodd.util.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lenovo on 2017/10/20.
 */
@Service
public class WmsBorrowCarServiceImpl implements WmsBorrowCarService {

    @Autowired
    private WmsBorrowCarMapper wmsBorrowCarMapper;

    @Autowired
    private WmsBorrowCarExtMapper wmsBorrowCarExtMapper;

    @Autowired
    private WmsBorrowCarDetailMapper wmsBorrowCarDetailMapper;

    @Autowired
    private WmsBorrowCarDetailExtMapper wmsBorrowCarDetailExtMapper;

    @Autowired
    private WmsInventoryExtMapper wmsInventoryExtMapper;

    @Autowired
    private WmsInventoryLocationExtMapper wmsInventoryLocationExtMapper;

    @Autowired
    private WmsInventoryLocationMapper wmsInventoryLocationMapper;

    @Autowired
    private WmsPreparationPlanMapper wmsPreparationPlanMapper;

    @Autowired
    private WmsPreparationVehicleDetailExtMapper wmsPreparationVehicleDetailExtMapper;

    @Autowired
    private WmsPreparationVehicleDetailCustomMapper wmsPreparationVehicleDetailCustomMapper;

    @Autowired
    private WmsPreparationPlanExtMapper wmsPreparationPlanExtMapper;

    @Autowired
    private WmsOutboundTaskExtMapper wmsOutboundTaskExtMapper;

    @Autowired
    private WmsBatchNoService wmsBatchNoService;

    @Autowired
    private SysUserRoleCustomMapper sysUserRoleCustomMapper;

    @Override
    public List<WmsBorrowCar> borrowLine(Map<String, Object> paramsMap) {
        List<WmsBorrowCar> wmsBorrowCarList = wmsBorrowCarExtMapper.borrowLine(paramsMap);
        for (WmsBorrowCar wmsBorrowCar : wmsBorrowCarList) {
            String downloadURL = QiniuUtil.generateDownloadURL(wmsBorrowCar.getUploadKey(), "");
            wmsBorrowCar.setUploadKey(downloadURL);
        }
        return wmsBorrowCarList;
    }

    @Override
    public Integer borrowLineCount(Map<String, Object> paramsMap) {
        return wmsBorrowCarExtMapper.borrowLineCount(paramsMap);
    }

    @Override
    public Integer borrowHistoryLineCount(Map<String, Object> paramsMap) {
        return wmsBorrowCarExtMapper.borrowReturnHistoryCount(paramsMap);
    }

    @Override
    public List<BorrowHistoryDTO> borrowHistoryLine(Map<String, Object> paramsMap) {
        return wmsBorrowCarExtMapper.borrowReturnHistory(paramsMap);
    }

    @Override
    public List<WmsBorrowCarDetail> findBorrowDetail(Long borrowId) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("deleteFlag", 1);
        paramsMap.put("bdBorrowId", borrowId);
        return wmsBorrowCarDetailExtMapper.findParams(paramsMap);
    }

    @Override
    public List<BorrowDetailDTO> queryModifyDetail(Long bcId) {
        List<BorrowDetailDTO> borrowDetailDTOList = wmsBorrowCarExtMapper.queryBorrowDetail(bcId);
        // 获取上传凭证的url
        for (BorrowDetailDTO borrowDetailDTO : borrowDetailDTOList) {
            String downloadURL = QiniuUtil.generateDownloadURL(borrowDetailDTO.getUploadKey(), "");
            borrowDetailDTO.setUploadPath(downloadURL);
        }
        return borrowDetailDTOList;
    }

    @Override
    public void add(WmsBorrowCar wmsBorrowCar, List<WmsBorrowCarDetail> wmsBorrowCarDetailList, Long userId) {
        // 查询操作的用户所属仓库信息
        List<UserWarehouseInfoDTO> userWarehouseInfoDTOList = sysUserRoleCustomMapper.userWarehouseInfo(userId);
        if (CollectionUtils.isEmpty(userWarehouseInfoDTOList))
            throw new BusinessException("用户所属仓库信息为空");
        UserWarehouseInfoDTO userWarehouseInfoDTO = userWarehouseInfoDTOList.get(0);
        if (userWarehouseInfoDTO == null)
            throw new BusinessException("用户所属仓库信息为空");

        // 批量插入的借车单明细
        List<WmsBorrowCarDetail> batchInsertDetail = new ArrayList<WmsBorrowCarDetail>();
        // 批量插入的备料计划明细
        List<WmsPreparationVehicleDetail> batchInsertPlanDetail = new ArrayList<WmsPreparationVehicleDetail>();
        // 检查借用车辆是否可以借用（1：检查是否有库存   2：库存是否存在备料计划中）
        for (WmsBorrowCarDetail wmsBorrowCarDetail : wmsBorrowCarDetailList) {
            // 查询车型和颜色的库存
            List<InventoryDetailDTO> inventoryDetailDTOList = new ArrayList<InventoryDetailDTO>();
            if (!StringUtils.isEmpty(wmsBorrowCarDetail.getBdVin())) {
                inventoryDetailDTOList = wmsInventoryExtMapper.queryByVin(wmsBorrowCarDetail.getBdVin());
                if (CollectionUtils.isEmpty(inventoryDetailDTOList)) {
                    throw new BusinessException("库存中不存在车架号为" + wmsBorrowCarDetail.getBdVin() + "的车辆可借用!");
                }
            } else {
                inventoryDetailDTOList = wmsInventoryExtMapper.queryBySpecAndColor(wmsBorrowCarDetail.getBdCarSpecname(), wmsBorrowCarDetail.getBdCarColorname());
                if (CollectionUtils.isEmpty(inventoryDetailDTOList)) {
                    throw new BusinessException("库存中不存在车型为" + wmsBorrowCarDetail.getBdCarSpecname() + "颜色为" + wmsBorrowCarDetail.getBdCarColorname() + "的车辆可借用!");
                }
            }
            // 获取不存在备料计划的所有库存
            List<InventoryDetailDTO> inventoryList = new ArrayList<InventoryDetailDTO>();
            for (InventoryDetailDTO inventoryDetailDTO : inventoryDetailDTOList) {
                // 查询车辆是否在备料计划中
                Integer count = wmsPreparationPlanExtMapper.queryByVin(inventoryDetailDTO.getInvlocVin());
                if (count == 0) {
                    inventoryList.add(inventoryDetailDTO);
                }
            }
            if (CollectionUtils.isEmpty(inventoryList)) {
                throw new BusinessException("该车辆已存在备料计划中!");
            }
            Integer borrowNum = (wmsBorrowCarDetail.getNum() == null) ? 0 : wmsBorrowCarDetail.getNum();
            if (borrowNum > inventoryList.size()) {
                throw new BusinessException("库存中车型为" + wmsBorrowCarDetail.getBdCarSpecname() + "颜色为" + wmsBorrowCarDetail.getBdCarColorname() + "的车辆数量不足借用数量!");
            }
        }

        // 新增借车单
        wmsBorrowCar.setGmtCreate(new Date());
        wmsBorrowCar.setDeleteFlag(true);
        wmsBorrowCarMapper.insert(wmsBorrowCar);
        // 更新生成的借车单号
        WmsBorrowCar updateBorrowCar = new WmsBorrowCar();
        updateBorrowCar.setBcBorrowNo(wmsBatchNoService.addSerialNum("BO", "BO"));
        updateBorrowCar.setBcId(wmsBorrowCar.getBcId());
        wmsBorrowCarMapper.updateByPrimaryKeySelective(updateBorrowCar);

        // 生成备料计划
        WmsPreparationPlan wmsPreparationPlan = new WmsPreparationPlan();
        wmsPreparationPlan.setBorrowNo(updateBorrowCar.getBcBorrowNo());
        wmsPreparationPlan.setPpStatus(String.valueOf(WmsPreparationPlanEnum.WMS_PLAN_NEW.getValue()));
        wmsPreparationPlan.setPpOutstockStatus(String.valueOf(WmsOutboundStatusEnum.WMS_OUTBOUND_NEW.getValue()));
        wmsPreparationPlan.setPpWhCode(userWarehouseInfoDTO.getWhCode());
        wmsPreparationPlan.setPpWhName(userWarehouseInfoDTO.getWhName());
        wmsPreparationPlan.setPpOutstockType(InboundOrderBusinessTypeEnum.Z7.getCode());
        wmsPreparationPlan.setGmtCreate(new Date());
        wmsPreparationPlan.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        wmsPreparationPlanMapper.insertSelective(wmsPreparationPlan);
        // 更新生成备料单号
        WmsPreparationPlan updatePlan = new WmsPreparationPlan();
        updatePlan.setPpId(wmsPreparationPlan.getPpId());
        WmsShipmentPlanServiceImpl wmsShipmentPlanService = new WmsShipmentPlanServiceImpl();
        updatePlan.setPpPreparationMaterialNo(wmsShipmentPlanService.createWmsPreparationPlanNo(wmsPreparationPlan.getPpId()));
        wmsPreparationPlanMapper.updateByPrimaryKeySelective(updatePlan);

        // 批量新增借车明细
        for (WmsBorrowCarDetail wmsBorrowCarDetail : wmsBorrowCarDetailList) {
            // 查询车型和颜色的库存
            List<InventoryDetailDTO> inventoryDetailDTOList = null;
            if (!StringUtils.isEmpty(wmsBorrowCarDetail.getBdVin())) {
                inventoryDetailDTOList = wmsInventoryExtMapper.queryByVin(wmsBorrowCarDetail.getBdVin());
            } else {
                inventoryDetailDTOList = wmsInventoryExtMapper.queryBySpecAndColor(wmsBorrowCarDetail.getBdCarSpecname(), wmsBorrowCarDetail.getBdCarColorname());
            }
            // 获取不存在备料计划的所有库存
            List<InventoryDetailDTO> inventoryList = new ArrayList<InventoryDetailDTO>();
            for (InventoryDetailDTO inventoryDetailDTO : inventoryDetailDTOList) {
                // 查询车辆是否在备料计划中
                Integer count = wmsPreparationPlanExtMapper.queryByVin(inventoryDetailDTO.getInvlocVin());
                if (count == 0) {
                    inventoryList.add(inventoryDetailDTO);
                }
            }
            // 获取借车单明细
            List<String> existInsert = new ArrayList<String>();
            Integer borrowNum = wmsBorrowCarDetail.getNum() == null ? 1 : wmsBorrowCarDetail.getNum();
            for (Integer num = 0; borrowNum > num; num++) {
                WmsBorrowCarDetail insertDetail = new WmsBorrowCarDetail();
                WmsPreparationVehicleDetail insertPlanDetail = new WmsPreparationVehicleDetail();
                BeanUtils.copyProperties(wmsBorrowCarDetail, insertDetail);
                for (InventoryDetailDTO canBorrow : inventoryList) {
                    Boolean have = false;
                    for (String vin : existInsert) {
                        if (vin.equals(canBorrow.getInvlocVin())) {
                            have = true;
                            break;
                        }
                    }
                    if (have == true) {
                        continue;
                    }
                    WmsInventoryLocation wmsInventoryLocation = new WmsInventoryLocation();
                    wmsInventoryLocation.setInvlocId(canBorrow.getInvlocId());
                    wmsInventoryLocation.setStatus(InventoryLocationStatusEnum.BORROW_LOCK_30.getCode());
                    wmsInventoryLocationMapper.updateByPrimaryKeySelective(wmsInventoryLocation);
                    insertDetail.setBdVin(canBorrow.getInvlocVin());
                    insertDetail.setBdWhcode(canBorrow.getInvlocWhCode());
                    insertDetail.setBdMaterialCode(canBorrow.getInvMaterialCode());
                    insertDetail.setBdMaterialName(canBorrow.getInvMaterialName());
                    insertDetail.setBdCarColorname(canBorrow.getInvColor());
                    insertDetail.setGmtCreate(new Date());
                    insertDetail.setBdBorrowId(wmsBorrowCar.getBcId());
                    insertDetail.setBdCarSpecname(canBorrow.getInvVehicleSpecName());
                    insertDetail.setBdCarSeries(canBorrow.getInvVehicleSeriesName());
                    insertDetail.setBdReturnStatus(10);
                    insertDetail.setDeleteFlag(1);
                    insertDetail.setNum(1);
                    existInsert.add(canBorrow.getInvlocVin());
                    insertPlanDetail.setVdPpId(updatePlan.getPpId());
                    insertPlanDetail.setHoHandoverNumber(updateBorrowCar.getBcBorrowNo());
                    insertPlanDetail.setVdVin(canBorrow.getInvlocVin());
                    insertPlanDetail.setVdVehicleName(canBorrow.getInvVehicleSpecName());
                    insertPlanDetail.setVdVehicleDesc(canBorrow.getInvVehicleSpecDesc());
                    insertPlanDetail.setVdWaybillNo(canBorrow.getInvlocWaybillNo());
                    insertPlanDetail.setVdOutstockStatus(String.valueOf(WmsOutboundStatusEnum.WMS_OUTBOUND_NEW.getValue()));
                    insertPlanDetail.setGmtCreate(new Date());
                    insertPlanDetail.setGmtUpdate(new Date());
                    insertPlanDetail.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
                    break;
                }
                batchInsertDetail.add(insertDetail);
                batchInsertPlanDetail.add(insertPlanDetail);
            }
        }
        // 批量插入借车单明细
        wmsBorrowCarDetailExtMapper.batchInsert(batchInsertDetail);
        // 批量插入备料计划明细
        wmsPreparationVehicleDetailExtMapper.batchInsert(batchInsertPlanDetail);
    }

    @Override
    public void modify(WmsBorrowCar wmsBorrowCar, List<WmsBorrowCarDetail> wmsBorrowCarDetailList) {
        // 校验是否借用车辆是否已经出库
        WmsBorrowCar borrowCar = wmsBorrowCarMapper.selectByPrimaryKey(wmsBorrowCar.getBcId());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("deleteFlag", 1);
        params.put("bdBorrowId", borrowCar.getBcId());
        List<WmsBorrowCarDetail> borrowCarDetailList = wmsBorrowCarDetailExtMapper.findParams(params);
        for (WmsBorrowCarDetail detail : borrowCarDetailList) {
            params = new HashMap<String, Object>();
            params.put("isDeleted", 1);
            params.put("invlocVin", detail.getBdVin());
            List<WmsInventoryLocation> wmsInventoryLocationList = wmsInventoryLocationExtMapper.findParams(params);
            if (CollectionUtils.isEmpty(wmsInventoryLocationList))
                throw new BusinessException("借车单已经出库，不能编辑");
        }

        // 更新借车单
        wmsBorrowCarMapper.updateByPrimaryKeySelective(wmsBorrowCar);

        // 根据车型和颜色查库存是否存在车辆
        for (WmsBorrowCarDetail wmsBorrowCarDetail : wmsBorrowCarDetailList) {
            if (wmsBorrowCarDetail.getBdId() == null) {
                List<InventoryDetailDTO> inventoryDetailDTOList = null;
                if (!StringUtil.isEmpty(wmsBorrowCarDetail.getBdVin())) {
                    inventoryDetailDTOList = wmsInventoryExtMapper.queryByVin(wmsBorrowCarDetail.getBdVin());
                    if (CollectionUtils.isEmpty(inventoryDetailDTOList))
                        throw new BusinessException("库存中不存在车架号为" + wmsBorrowCarDetail.getBdVin() + "的车辆可借用!");
                } else {
                    inventoryDetailDTOList = wmsInventoryExtMapper.queryBySpecAndColor(wmsBorrowCarDetail.getBdCarSpecname(), wmsBorrowCarDetail.getBdCarColorname());
                    if (CollectionUtils.isEmpty(inventoryDetailDTOList))
                        throw new BusinessException("库存中不存在车型为" + wmsBorrowCarDetail.getBdCarSpecname()
                                + "颜色为" + wmsBorrowCarDetail.getBdCarColorname()
                                + "的车辆可借用!");
                }

                Boolean have = false;
                Boolean insufficientQuantity = false;
                for (InventoryDetailDTO inventoryDetailDTO : inventoryDetailDTOList) {
                    // 查询车辆是否在备料计划中
                    Integer count = wmsPreparationPlanExtMapper.queryByVin(inventoryDetailDTO.getInvlocVin());
                    if (count == 0) {
                        insufficientQuantity = true;
                        // 获取车辆在存存中数量
                        Integer num = inventoryDetailDTO.getInvNum();
                        num = (num == null) ? 0 : num;
                        // 查询未归还的数量
                        List<Integer> notReturn = wmsBorrowCarDetailExtMapper.queryNumBySpecAndColor(wmsBorrowCarDetail.getBdCarSpecname(), wmsBorrowCarDetail.getBdCarColorname());
                        Integer notResultNum = 0;
                        for (Integer i : notReturn) {
                            i = (i == null) ? 0 : i;
                            notResultNum += i;
                        }
                        if (num == null || num < (wmsBorrowCarDetail.getNum() + notResultNum)) {
                            continue;
                        }
                        have = true;
                        break;
                    }
                }

                // 库存中的车辆数量不足借用数量
                if (insufficientQuantity == true && have == false)
                    throw new BusinessException("库存中车型为：" + wmsBorrowCarDetail.getBdCarSpecname()
                            + "颜色为：" + wmsBorrowCarDetail.getBdCarColorname()
                            + "的车辆数量不足借用数量!");

                // 车辆在备料计划中,不可借车
                if (have == false)
                    throw new BusinessException("库存中车型为：" + wmsBorrowCarDetail.getBdCarSpecname()
                            + "颜色为：" + wmsBorrowCarDetail.getBdCarColorname()
                            + "的车辆已经存在备料计划中，不能借用!");
            }
        }

        // 查询未更新前的明细
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("deleteFlag", 1);
        paramsMap.put("bdReturnStatus", 10);
        paramsMap.put("bdBorrowId", wmsBorrowCar.getBcId());
        List<WmsBorrowCarDetail> detailsBefore = wmsBorrowCarDetailExtMapper.findParams(paramsMap);

        // 判断编辑是否有删除明细
        List<Long> idList = new ArrayList<Long>();
        List<String> delVinList = new ArrayList<String>();
        for (WmsBorrowCarDetail detail : detailsBefore) {
            Boolean have = false;
            for (WmsBorrowCarDetail detail1 : wmsBorrowCarDetailList) {
                if (detail.getBdId().equals(detail1.getBdId())) {
                    have = true;
                    break;
                }
            }
            // 如果存在删除明细
            if (have == false) {
                idList.add(detail.getBdId());
                delVinList.add(detail.getBdVin());
            }
        }
        if (!CollectionUtils.isEmpty(idList)) {
            // 删除借车单明细
            wmsBorrowCarDetailExtMapper.deleteDetail(idList, null);
        }
        if (!CollectionUtils.isEmpty(delVinList)) {
            // 删除出库任务
            wmsOutboundTaskExtMapper.deleteByVin(delVinList);
        }
        if (!CollectionUtils.isEmpty(delVinList)) {
            // 更新库存车辆状态为正常在库
            wmsInventoryLocationExtMapper.updateStatusByVinList(10, delVinList);
        }

        // 获取新增加的借车单明细
        List<WmsBorrowCarDetail> addBorrowCarDetailList = new ArrayList<WmsBorrowCarDetail>();
        for (WmsBorrowCarDetail wmsBorrowCarDetail : wmsBorrowCarDetailList) {
            if (wmsBorrowCarDetail.getBdId() == null) {
                addBorrowCarDetailList.add(wmsBorrowCarDetail);
            }
        }

        // 插入新增加的借车单明细
        for (WmsBorrowCarDetail addBorrowCarDetail : addBorrowCarDetailList) {
            // 批量插入的借车单明细
            List<WmsBorrowCarDetail> batchInsertDetail = new ArrayList<WmsBorrowCarDetail>();
            // 批量插入出库任务
            List<WmsOutboundTask> batchInsertOutTask = new ArrayList<WmsOutboundTask>();
            // 车型和颜色的明细数量
            Integer borrowNum = addBorrowCarDetail.getNum();

            List<InventoryDetailDTO> inventoryList = null;
            // 查询车型和颜色的库存
            if (!StringUtils.isEmpty(addBorrowCarDetail.getBdVin())) {
                inventoryList = wmsInventoryExtMapper.queryByVin(addBorrowCarDetail.getBdVin());
            } else {
                inventoryList = wmsInventoryExtMapper.queryBySpecAndColor(addBorrowCarDetail.getBdCarSpecname(), addBorrowCarDetail.getBdCarColorname());
            }

            // 获取不存在备料计划的库存
            List<InventoryDetailDTO> canBorrowInventoryList = new ArrayList<InventoryDetailDTO>();
            for (InventoryDetailDTO inventory : inventoryList) {
                Integer count = wmsPreparationPlanExtMapper.queryByVin(inventory.getInvlocVin());

                // count==0就是该库存不存在备料计划中，则判断库存中的数量是否足够借用
                if (count == 0) {
                    // 获取车辆在库存中数量
                    Integer num = inventory.getInvNum();
                    // 查询未归还的数量
                    List<Integer> notReturn = wmsBorrowCarDetailExtMapper.queryNumBySpecAndColor(addBorrowCarDetail.getBdCarSpecname(), addBorrowCarDetail.getBdCarColorname());
                    Integer notReturnNum = 0;
                    for (Integer i : notReturn) {
                        i = (i == null) ? 0 : i;
                        notReturnNum += i;
                    }
                    if (num != null || num >= (borrowNum + notReturnNum)) {
                        canBorrowInventoryList.add(inventory);
                    }
                }
            }

            // 获取借车单明细
            List<String> existInsert = new ArrayList<String>();
            for (Integer num = 0; borrowNum > num; num++) {
                WmsBorrowCarDetail insertDetail = new WmsBorrowCarDetail();
                WmsOutboundTask wmsOutboundTask = new WmsOutboundTask();
                BeanUtils.copyProperties(addBorrowCarDetail, insertDetail);
                for (InventoryDetailDTO canBorrow : canBorrowInventoryList) {
                    Boolean have = false;
                    for (String vin : existInsert) {
                        if (vin.equals(canBorrow.getInvlocVin())) {
                            have = true;
                            break;
                        }
                    }
                    if (have == true)
                        continue;

                    insertDetail.setBdVin(canBorrow.getInvlocVin());
                    insertDetail.setBdMaterialCode(canBorrow.getInvMaterialCode());
                    insertDetail.setBdCarColorname(canBorrow.getInvColor());
                    insertDetail.setGmtCreate(new Date());
                    insertDetail.setBdBorrowId(wmsBorrowCar.getBcId());
                    insertDetail.setBdReturnStatus(10);
                    insertDetail.setDeleteFlag(1);
                    insertDetail.setNum(1);
                    existInsert.add(canBorrow.getInvlocVin());
                    wmsOutboundTask.setOtVin(canBorrow.getInvlocVin());
                    wmsOutboundTask.setOtZoneCode(canBorrow.getInvlocZoneCode());
                    wmsOutboundTask.setOtZoneName(canBorrow.getInvlocZoneName());
                    wmsOutboundTask.setOtLocationCode(canBorrow.getInvlocLocCode());
                    wmsOutboundTask.setOtLcoationName(canBorrow.getInvlocLocName());
                    wmsOutboundTask.setOtStatus(String.valueOf(WmsOutboundTaskStatusEnum.WMS_OUTBOUND_TASK_STATUS_NEW.getValue()));
                    wmsOutboundTask.setInspectStatus(WmsOutboundInspectStatusEnum.WAYBILL_INIT.getValue());
                    wmsOutboundTask.setOtSupplierVsCode(canBorrow.getInvVehicleSpecCode());
                    wmsOutboundTask.setOtSupplierVsName(canBorrow.getInvVehicleSpecName());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    wmsOutboundTask.setOtTaskNo("TA" + sdf.format(new Date()));
                    if (!CollectionUtils.isEmpty(batchInsertOutTask)) {
                        wmsOutboundTask.setOtPreparationMaterialNo(batchInsertOutTask.get(0).getOtPreparationMaterialNo());
                    } else {
                        wmsOutboundTask.setOtPreparationMaterialNo("P" + sdf.format(new Date()));
                    }
                    break;
                }
                batchInsertDetail.add(insertDetail);
                batchInsertOutTask.add(wmsOutboundTask);
            }
            // 批量插入借车单明细
            wmsBorrowCarDetailExtMapper.batchInsert(batchInsertDetail);
            // 批量插入出库任务
            wmsOutboundTaskExtMapper.batchInsert(batchInsertOutTask);
        }
    }

    @Override
    public void delete(List<Long> ids) {
        List<String> vinList = new ArrayList<String>();
        for (Long id : ids) {
            WmsBorrowCar wmsBorrowCar = wmsBorrowCarMapper.selectByPrimaryKey(id);
            // 校验是否借用车辆是否已经出库
            WmsBorrowCar borrowCar = wmsBorrowCarMapper.selectByPrimaryKey(wmsBorrowCar.getBcId());
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("deleteFlag", 1);
            params.put("bdBorrowId", borrowCar.getBcId());
            List<WmsBorrowCarDetail> borrowCarDetailList = wmsBorrowCarDetailExtMapper.findParams(params);
            for (WmsBorrowCarDetail detail : borrowCarDetailList) {
                params = new HashMap<String, Object>();
                params.put("isDeleted", 1);
                params.put("invlocVin", detail.getBdVin());
                List<WmsInventoryLocation> wmsInventoryLocationList = wmsInventoryLocationExtMapper.findParams(params);
                if (CollectionUtils.isEmpty(wmsInventoryLocationList)) {
                    throw new BusinessException("借车单" + wmsBorrowCar.getBcBorrowNo() + "已经出库，不能删除");
                }
                vinList.add(detail.getBdVin());
            }
        }

        // 批量查询借车单信息
        List<WmsBorrowCar> wmsBorrowCarList = wmsBorrowCarExtMapper.batchSelectByIds(ids);

        // 获取所有借车单的单号
        List<String> borrowNoList = new ArrayList<String>();
        for (WmsBorrowCar wmsBorrowCar : wmsBorrowCarList) {
            borrowNoList.add(wmsBorrowCar.getBcBorrowNo());
        }

        // 删除借车单
        wmsBorrowCarExtMapper.deleteBorrow(ids);
        // 删除借车单明细
        wmsBorrowCarDetailExtMapper.deleteDetail(ids, null);
        // 删除备料计划
        wmsPreparationPlanExtMapper.batchDeleteByBorrowNo(borrowNoList);
        // 删除备料计划明细
        wmsPreparationVehicleDetailCustomMapper.batchDeleteDetailByVin(vinList);
        // 更新库存车辆状态为正常在库
        wmsInventoryLocationExtMapper.updateStatusByVinList(10, vinList);
    }

    @Override
    public BorrowPrintDetailDTO printInfo(Long bcId) {
        BorrowPrintDetailDTO borrowPrintDetailDTO = null;
        try {
            borrowPrintDetailDTO = wmsBorrowCarExtMapper.queryPrintInfo(bcId);
            // 将借用日期格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            borrowPrintDetailDTO.setBorrowDate(sdf.format(borrowPrintDetailDTO.getBcBorrowDate()));

            BarCodeBO barCodeBO = new BarCodeBO();

            WmsBorrowCar wmsBorrowCar = wmsBorrowCarMapper.selectByPrimaryKey(bcId);
            if (wmsBorrowCar != null) {
                barCodeBO.setOrderNo(wmsBorrowCar.getBcBorrowNo());
            }

            // 查询借车单明细
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("deleteFlag", 1);
            paramsMap.put("bdBorrowId", bcId);
            List<WmsBorrowCarDetail> wmsBorrowCarDetailList = wmsBorrowCarDetailExtMapper.findParams(paramsMap);

            // 获取借车单的所有车架号
            List<String> vins = new ArrayList<String>();
            if (!CollectionUtils.isEmpty(wmsBorrowCarDetailList)) {
                for (WmsBorrowCarDetail wmsBorrowCarDetail : wmsBorrowCarDetailList) {
                    vins.add(wmsBorrowCarDetail.getBdVin());
                }
            }

            String text = borrowPrintDetailDTO.getBcBorrowNo();
            BufferedImage qrImageBuffer = ZxingEAN13Handler.toBufferedImage(ZxingEAN13Handler.encode(text, 200, 50));
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(qrImageBuffer, "png", os);
            String base64Img = new Base64().encodeToString(os.toByteArray());
            //BASE64Encoder base64 = new BASE64Encoder();
            //String base64Img = new String(base64.encode(os.toByteArray()));

            borrowPrintDetailDTO.setBase64Img(base64Img);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return borrowPrintDetailDTO;
    }

    /**
     * 根据车架号获取信息
     *
     * @param vin
     * @return
     * @throws Exception
     */
    @Override
    public WmsBorrowCarDetail getBorrowCarDetailByVin(String vin) throws Exception {
        if (StringUtils.isNotBlank(vin)) {

            WmsBorrowCarDetailExample example = new WmsBorrowCarDetailExample();
            example.createCriteria().andBdVinEqualTo(vin);
            List<WmsBorrowCarDetail> carDetailList = wmsBorrowCarDetailMapper.selectByExample(example);
            if (CollectionUtils.isNotEmpty(carDetailList)) {
                return carDetailList.get(0);
            }
        }
        return null;
    }

    /**
     * 根据借车单号获取借车详情
     *
     * @param borrowNo
     * @return
     * @throws Exception
     */
    @Override
    public List<WmsBorrowCarDetail> getBorrowCarDetaiListByBorrowNo(String borrowNo) throws Exception {
        if (StringUtils.isNotBlank(borrowNo)) {

            WmsBorrowCarExample example = new WmsBorrowCarExample();
            example.createCriteria().andBcBorrowNoEqualTo(borrowNo);
            List<WmsBorrowCar> borrowCarList = wmsBorrowCarMapper.selectByExample(example);
            List<Long> idList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(borrowCarList)) {
                borrowCarList.stream()
                        .filter(borrow -> borrow != null && borrow.getBcId() != null)
                        .forEach(borrow -> idList.add(borrow.getBcId()));
            }
            if (CollectionUtils.isNotEmpty(idList)) {
                WmsBorrowCarDetailExample detailExample = new WmsBorrowCarDetailExample();
                detailExample.createCriteria().andBdBorrowIdIn(idList);
                return wmsBorrowCarDetailMapper.selectByExample(detailExample);
            }
        }
        return null;
    }

    /**
     * 根据id获取借车单
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public WmsBorrowCar getWmsBorrowCarById(Long id) throws Exception {
        if (id != null) {
            return wmsBorrowCarMapper.selectByPrimaryKey(id);
        }
        return null;
    }

    /**
     * 根据车架号更新状态
     *
     * @param vin
     * @param status
     * @throws Exception
     */
    @Override
    public void updateDetailStatusByVin(String vin, Integer status) throws Exception {
        if (StringUtils.isNotBlank(vin)) {
            WmsBorrowCarDetail detail = new WmsBorrowCarDetail();
            detail.setBdReturnStatus(status);

            WmsBorrowCarDetailExample example = new WmsBorrowCarDetailExample();
            example.createCriteria().andBdVinEqualTo(vin);

            wmsBorrowCarDetailMapper.updateByExampleSelective(detail, example);
        }
    }
}
